package com.xmindguoguo.boot.modular;

import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xmindguoguo.boot.common.constant.SessionConstant;
import com.xmindguoguo.boot.core.BaseController;
import com.xmindguoguo.boot.core.log.LogManager;
import com.xmindguoguo.boot.core.log.factory.LogTaskFactory;
import com.xmindguoguo.boot.core.shiro.ShiroKit;
import com.xmindguoguo.boot.util.http.IpUtils;
import com.xmindguoguo.boot.util.json.JsonResult;

@Controller
@RequestMapping
public class LoginController extends BaseController {
    // 没有权限的跳转
    @RequestMapping("/common/unauthorized")
    public String unauthorized() {
        return "/common/unauthorized";
    }

    /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + "/";
        } else {
            return "login"; // 卧槽奇了怪了，不加html 还不出页面
        }
    }

    /**
     * 点击登录执行的动作
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult loginVali(String username, String password, String code,
            @RequestParam(value = "remember", required = false) String remember) {
        // 获取session中的验证码
        String sessionCode = (String) request.getSession().getAttribute(SessionConstant.CAPTCHA);
        // 判断验证码
        if (code == null || !sessionCode.equals(code.trim().toLowerCase())) {
            return JsonResult.sendError("验证码不正确");
        }
        String msg = "登陆成功";
        try {
            Subject currentUser = ShiroKit.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(username, password.toCharArray());
            if ("on".equalsIgnoreCase(remember)) { // 暂时默认记住密码
                token.setRememberMe(true);
            } else {
                token.setRememberMe(false);
            }
            currentUser.login(token);
//            request.getSession().setAttribute("username", shiroUser.getAccount());
            ShiroKit.getSession().setAttribute("sessionFlag", true);
        } catch (UnknownAccountException e) {
            msg = "账户不存在！或者密码错误！"; // msg = "账户不存在！";
        } catch (IncorrectCredentialsException e) {
            msg = "账户不存在！或者密码错误！"; // msg = "密码错误！";
        } catch (LockedAccountException e) {
            msg = "您的账户已被锁定,请与管理员联系！";
        } catch (ExcessiveAttemptsException e) {
            msg = "登录失败次数过多,请稍后再试！";
        } catch (Exception e) {
            msg = "系统发生错误，请联系管理员！";
        }
        String ip = IpUtils.getIpAddr(request);
        String userAgentStr = request.getHeader("User-Agent");
        LogManager.me().executeLog(LogTaskFactory.loginLog(ip, userAgentStr, username, password, msg));
        // 是否登录成功
        if (msg.equals("登陆成功")) {
            return JsonResult.sendOk(msg, null);
        } else {
            return JsonResult.sendError(msg, null);
        }
    }

    /**
     * 退出
     */
    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String logout() {
        ShiroKit.getSubject().logout();
        return REDIRECT + "/login";
    }

    /**
     * 退出
     */
    @RequestMapping(value = "ajaxLogout")
    @ResponseBody
    public JsonResult ajaxLogout() {
        ShiroKit.getSubject().logout();
        return JsonResult.sendOk("退出成功");
    }

}
